/**
 * 
 */
package com.lamp.customer.server.hander;

import java.util.HashMap;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lamp.constant.Command;
import com.lamp.customer.bs.AuthReqBody;
import com.lamp.customer.manager.HeartStatusManager;
import com.lamp.customer.server.ILampAioHandlerIntf;
import com.sieman.common.protocol.ImPacket;
import com.talent.aio.common.Aio;
import com.talent.aio.common.ChannelContext;


/**
 * 
 * @ClassName: HeartbeatHandler
 * @Description: 心跳鉴权处理
 * @author  kangjie1209@126.com
 * @date 2017年1月16日 下午2:47:14
 *
 */
public class HeartbeatHandler implements ILampAioHandlerIntf
{
	private static Logger log = LoggerFactory.getLogger(HeartbeatHandler.class);
	
	/**心跳状态检测工具类**/
	private HashMap<String, HeartStatusManager> heartStatusCache = new HashMap<String, HeartStatusManager>();
	
	/**
	 * 
	 */
	public HeartbeatHandler()
	{

	}

	@Override
	public Object handler(ImPacket packet, ChannelContext<Object, ImPacket, Object> channelContext) throws Exception
	{
		String bodyStr = null;
		if (packet.getBody() != null)
		{
			bodyStr = new String(packet.getBody(), ImPacket.CHARSET);
		}
		
		if (log.isInfoEnabled())
		{
			log.info("{}收到鉴权包:{}", channelContext.toString(), bodyStr);
		}
		
		//AuthReqBody authReqBody = Json.toBean(bodyStr, AuthReqBody.class);
		/*AuthReqBody authReqBody = null;
		String token = authReqBody.getToken();
		String deviceId = authReqBody.getDeviceId();
		String deviceInfo = authReqBody.getDeviceInfo();
		Long seq = authReqBody.getSeq();
		String sign = authReqBody.getSign();

		String loginname = null;//authReqBody.getLoginname();
		String pwd = null;//authReqBody.getPwd();

		if (StringUtils.isBlank(deviceId))
		{
			Aio.close(channelContext, "did is null");
			return null;
		}

		if (seq == null)
		{
			Aio.close(channelContext, "seq is null");
			return null;
		}*/


		//		did = did == null ? "" : did;
	/*	token = token == null ? "" : token;
		deviceInfo = deviceInfo == null ? "" : deviceInfo;
		//		seq = seq == null ? 0 : seq;

		String data = token + deviceId + deviceInfo + seq + com.talent.aio.examples.im.common.Const.authkey;

		try
		{
			String _sign = Md5.getMD5(data);
			if (!_sign.equals(sign))
			{
				log.error("sign is invalid, {}, actual sign:{},expect sign:{}", channelContext.toString(), sign, _sign);
				Aio.close(channelContext, "sign is invalid");
				return null;
			}
		} catch (Exception e)
		{
			log.error(e.toString(), e);
			Aio.close(channelContext, e.getMessage());
			return null;
		}*/

		//Byte type = authReqBody.getDeviceType();
		byte[] body = new byte[]{0x01,0x01,0x01,0x01,0x01,0x01,0x01};
		ImPacket imRespPacket = new ImPacket(body,(short)1);
		imRespPacket.setCommand(Command.AUTH_RESP);
		
		Aio.send(channelContext, imRespPacket);
		return null;
	}
}
